package com.ec.auth.security.filter;

import com.ec.auth.web.service.TokenService;
import com.ec.common.core.domain.model.LoginUser;
import com.ec.common.utils.SecurityUtils;
import com.ec.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.security.sasl.AuthenticationException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器 验证token有效性
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        // 获取请求携带的令牌
        String token = tokenService.getToken(request);

        // 如果为空直接放行
        if (StringUtils.isEmpty(token)) {
            chain.doFilter(request, response);
            return;
        }

        // 获取用户信息
        LoginUser loginUser = tokenService.getLoginUser(token);
        if (StringUtils.isNull(loginUser)) {
            throw new BadCredentialsException("令牌无效");
        }

        if (StringUtils.isNull(SecurityUtils.getAuthentication())) {
//            //判断tenant是否与令牌信息一致
            String tenant = request.getHeader("tenant");
            if (!loginUser.getTenant().equalsIgnoreCase(tenant)) {
                throw new BadCredentialsException("令牌无效");
            }

            // 刷新令牌有效期
            tokenService.verifyToken(loginUser);
            // 认证
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }

        chain.doFilter(request, response);
    }
}
